package com.ccrego.haiyi.account.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ccrego.haiyi.R;
import com.ccrego.haiyi.account.Account;
import com.ccrego.haiyi.account.AccountManager;
import com.ccrego.haiyi.account.ParamKey;
import com.ccrego.haiyi.account.UrlCenter;
import com.ccrego.haiyi.app.MainActivity;
import com.ccrego.haiyi.common.http.MyHttpRequest;
import com.ccrego.haiyi.common.http.TokenInfo;
import com.ccrego.haiyi.utils.FragmentUtils;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.customviews.edittext.PasswordEditText;
import com.pachong.android.frameworkbase.dialog.ProgressFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;
import com.pachong.android.frameworkbase.utils.MD5Util;
import com.pachong.android.frameworkbase.utils.RegularUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class RegisterActivity extends BaseActivity {

    @Bind(R.id.itetPhone)
    EditText mItetPhone;
    @Bind(R.id.itetCode)
    EditText mItetCode;
    @Bind(R.id.itetPassword)
    PasswordEditText mItetPassword;
    private static final int CATPCHA_TYPE_REGISTER = 1;
    @Bind(R.id.itetPassword_again)
    PasswordEditText mItetPasswordAgain;
    private MyCountDownTimer mc;
    @Bind(R.id.getCode)
    TextView mGetCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolsBar();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (mc != null) {
            mc.cancel();
        }
    }

    private void initToolsBar() {
        setTitle(R.string.register);
        getCustomToolbar().addLeftImageButton(R.mipmap.icon_back1, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mc != null) {
                    mc.cancel();
                }
                LoginActivity.start(getApplicationContext());
                finish();
            }
        });

    }

    public static void start(Activity activity) {
        Intent intent = new Intent(activity, RegisterActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_register, null);
    }

    private String getPhone() {
        return mItetPhone.getText().toString().trim();
    }


    private String getPassWordAgain() {
        return mItetPasswordAgain.getEditText().toString().trim();
    }
    private String getPassWord() {
        return mItetPassword.getEditText().toString().trim();
    }

    private String getYzm() {
        return mItetCode.getText().toString().trim();
    }

    @OnClick({R.id.getCode, R.id.rl_regist_agreement, R.id.btn_regist, R.id.tv_regist_login, R.id.tv_agreement})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //获得验证码
            case R.id.getCode:
                sendCheckCode();
                break;
            //用户协议
            case R.id.rl_regist_agreement:
                break;
            //注册并登录
            case R.id.btn_regist:
                isCodeExist();
                break;
            //直接登录
            case R.id.tv_regist_login:
                if (mc != null) {
                    mc.cancel();
                }
                LoginActivity.start(RegisterActivity.this);
                finish();
                break;
            case R.id.tv_agreement:
                AgreementActivity.start(RegisterActivity.this);
                break;
        }
    }

    private void isCodeExist() {
        if (TextUtils.isEmpty(getPhone())) {
            FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getPassWord())) {
            FragmentUtils.showWarnDialog("密码不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getPassWordAgain())) {
            FragmentUtils.showWarnDialog("密码不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getYzm())) {
            FragmentUtils.showWarnDialog("请输入验证码", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getPhone())) {
            FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isPassword(getPassWord())) {
            FragmentUtils.showWarnDialog("密码首位需为字母或数字,且最少6位", getSupportFragmentManager());
            return;
        }else if(getPassWord().equals(getPassWordAgain())==false){
            FragmentUtils.showWarnDialog("两次密码输入不相同", getSupportFragmentManager());
            return;
        }
        HttpRequest request = new HttpRequest(getBaseContext());
        String UrlIsExist = String.format(UrlCenter.ISCodeExist, getPhone(), CATPCHA_TYPE_REGISTER, getYzm());
        request.get(UrlIsExist, null, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                try {
                    JSONObject joj = new JSONObject(o);
                    String error = joj.getString("error");
                    if(error.equals("验证码错误")==true){
                        EasyToast.showToast(getApplicationContext(),"验证码错误");
                    }else{
                        putRegist();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(RegisterActivity.this, strMsg);

            }
        });


    }

    //上传注册
    private void putRegist() {
        if (TextUtils.isEmpty(getPhone())) {
            FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getPassWord())) {
            FragmentUtils.showWarnDialog("密码不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getPassWordAgain())) {
            FragmentUtils.showWarnDialog("密码不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getYzm())) {
            FragmentUtils.showWarnDialog("请输入验证码", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getPhone())) {
            FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isPassword(getPassWord())) {
            FragmentUtils.showWarnDialog("密码最多为6-25个字符", getSupportFragmentManager());
            return;
        }else if(getPassWord().equals(getPassWordAgain())==false){
            FragmentUtils.showWarnDialog("密码首位需为字母或数字,且最少6位", getSupportFragmentManager());
            return;
        }

        putMessage();
    }

    private void putMessage() {
        HttpRequest request = new HttpRequest(RegisterActivity.this);
        JSONObject jobj = new JSONObject();
        final String enCodePwd = MD5Util.getMd5(getPassWord());
        final String enCodePwdAgain = MD5Util.getMd5(getPassWordAgain());
        try {
            jobj.put(ParamKey.LOGIN_NAME, getPhone());
            jobj.put(ParamKey.RE_PASSWORD, enCodePwdAgain);
            jobj.put(ParamKey.PASSWORD, enCodePwd);
            jobj.put(ParamKey.CAPTCHA, getYzm());
            request.post(UrlCenter.REGISTER, jobj, new DataRequestListener<Account>(Account.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(Account o) {
                    super.onSuccess(o);
                    EasyToast.showToast(RegisterActivity.this, "注册成功!");
                    setLoginRequest(getPhone());
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(RegisterActivity.this, strMsg);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    //注册完成马上登陆
    private void setLoginRequest(String phone) {
        HttpRequest request = new HttpRequest(this);
        JSONObject jobj = new JSONObject();
        final String enCodePwd = MD5Util.getMd5(getPassWord());
        try {
            jobj.put(ParamKey.LOGIN_NAME, phone);
            jobj.put(ParamKey.PASSWORD, enCodePwd);
            if (!progressFragment.isVisible()) {
                progressFragment.show(getSupportFragmentManager());
            }
            request.post(UrlCenter.LOGIN, jobj, new DataRequestListener<TokenInfo>(TokenInfo.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onSuccess(TokenInfo tokenInfo) {
                    super.onSuccess(tokenInfo);
                    AccountManager.updateTokenInfo(tokenInfo);
                    setAccount();
                    if (progressFragment.isVisible()) {
                        progressFragment.dismiss();
                    }
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
//                    EasyToast.showToast(getContext(),strMsg);
                    if (progressFragment.isVisible()) {
                        progressFragment.dismiss();
                    }
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setAccount() {
        IHttpRequest request = new MyHttpRequest(this);
        String requestUrl = String.format(UrlCenter.USER);
        request.get(requestUrl, null, new DataRequestListener<Account>(Account.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(Account account) {
                Log.e("zf", "Account : " + account);
                account.setPassWord(MD5Util.getMd5("" + getPassWord()));
                AccountManager.setCurrentAccount(account);
                EasyToast.showToast(RegisterActivity.this, "登录成功");
                MainActivity.start(RegisterActivity.this);
                if (mc != null) {
                    mc.cancel();
                }
                finish();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    private void sendCheckCode() {
        if (TextUtils.isEmpty(getPhone())) {
            FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getPhone())) {
            FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
            return;
        }
        //先判断是否注册过
        isRegist();

//
    }

    private void isRegist() {
        HttpRequest request = new HttpRequest(this);
        String UrlIsExist = String.format(UrlCenter.ISEXIST, getPhone());
        Log.e("UrlIsExist", UrlIsExist);
        request.get(UrlIsExist, null, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String o) {
                super.onSuccess(o);
                try {
                    JSONObject jsonObject = new JSONObject(o);
                    boolean isExist = jsonObject.optBoolean("value");
                    if (isExist) {
                        EasyToast.showToast(RegisterActivity.this, "该账号已注册");
                    } else {
                        sendMessage();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                EasyToast.showToast(RegisterActivity.this, strMsg);
            }
        });
    }

    private void sendMessage() {
        HttpRequest request = new HttpRequest(this);
        JSONObject jobj = new JSONObject();
        String UrlCaptcha = String.format(UrlCenter.CAPTCHA, getPhone(), CATPCHA_TYPE_REGISTER);
        try {
            jobj.put(ParamKey.PHONE, getPhone());
            jobj.put(ParamKey.TYPE, CATPCHA_TYPE_REGISTER);
            request.post(UrlCaptcha, jobj, new DataRequestListener<Object>(Object.class) {
                @Override
                public void onStart(Context context, String url) {
                    super.onStart(context, url);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    super.onFailure(t, errorNo, strMsg);
                    EasyToast.showToast(RegisterActivity.this, strMsg);
                }

                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);
                    EasyToast.showToast(RegisterActivity.this, "发送验证码成功!");
                    mGetCode.setClickable(false);
                    mc = new MyCountDownTimer(60000, 1000);
                    mc.start();
                    dismissProgress();
                }
            });


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }




    /**
     * 继承 CountDownTimer 防范
     * <p>
     * 重写 父类的方法 onTick() 、 onFinish()
     */
    class MyCountDownTimer extends CountDownTimer {
        /**
         * @param millisInFuture    表示以毫秒为单位 倒计时的总数
         *                          <p>
         *                          例如 millisInFuture=1000 表示1秒
         * @param countDownInterval 表示 间隔 多少微秒 调用一次 onTick 方法
         *                          <p>
         *                          例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick()
         */
        public MyCountDownTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mGetCode.setText("重新获取");
            if (!TextUtils.isEmpty(mGetCode.getText())) {
                mGetCode.setClickable(true);
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {
            if (mGetCode != null) {
                mGetCode.setText(millisUntilFinished / 1000 + "s");
            }
        }
    }

    //返回键设置
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mc != null) {
                mc.cancel();
            }
            LoginActivity.start(RegisterActivity.this);
            finish();
        }
        return true;
    }

    //显示加载图标
    private ProgressFragment progressFragment = new ProgressFragment();

    private void showProgress() {
        if (!progressFragment.isVisible()) {
            progressFragment.show(getSupportFragmentManager());
        }
    }

    // 隐藏加载图标
    private void dismissProgress() {
        if (progressFragment.isVisible()) {
            progressFragment.dismiss();
        }
    }
}
